import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ProductCard from './ProductCard';
import { ApiService } from '../services/api';
import './ProductSection.css';
import { Spin } from 'antd';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';

const ProductSection = () => {
  const navigate = useNavigate();
  const [hotProducts, setHotProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [industryNews, setIndustryNews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [newsLoading, setNewsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newsError, setNewsError] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);

  // 跳转到产品中心
  const handleViewMore = (filterType = null, categoryId = null) => {
    const params = new URLSearchParams();
    if (filterType) {
      params.set('filter', filterType);
    }
    if (categoryId) {
      params.set('categoryId', categoryId);
    }
    const queryString = params.toString();
    navigate(`/products${queryString ? `?${queryString}` : ''}`);
  };

  // 跳转到新闻详情页
  const handleNewsClick = (newsId) => {
    navigate(`/news/${newsId}`);
  };

  // 获取热门产品数据
  useEffect(() => {
    if (isInitialized) return;
    
    const fetchHotProducts = async () => {
      try {
        setLoading(true);
        const response = await ApiService.getHotProductList();
        
        if (response.code === '0000' && response.data) {
          // 按serNum排序并转换为组件需要的格式
          const sortedProducts = response.data
            .sort((a, b) => a.serNum - b.serNum)
            .map(product => ({
              id: product.productId,
              title: product.productName,
              description: `${product.productSimDesc || ''}`,
              image: product.picUrl,
              picUrl: product.picUrl // 保存原始图片URL
            }));
          setHotProducts(sortedProducts);
        } else {
          setError('获取热门产品数据失败');
        }
      } catch (err) {
        console.error('获取热门产品失败:', err);
        setError('网络请求失败，使用默认产品数据');
        // 设置默认产品数据
        setHotProducts([]);
      } finally {
        setLoading(false);
        setIsInitialized(true);
      }
    };

    fetchHotProducts();
  }, [isInitialized]);

  // 获取行业资讯数据
  useEffect(() => {
    const fetchIndustryNews = async () => {
      try {
        setNewsLoading(true);
        const response = await ApiService.getIndustryNewsList();
        
        if (response.code === '0000' && response.data) {
          // 按serNum排序并格式化日期
          const sortedNews = response.data
            .sort((a, b) => a.serNum - b.serNum)
            .map(news => ({
              id: news.newsId,
              title: news.newsTitle,
              date: news.newsTime ? news.newsTime : '',
              serNum: news.serNum
            }));
          setIndustryNews(sortedNews);
        } else {
          setNewsError('获取行业资讯数据失败');
        }
      } catch (err) {
        console.error('获取行业资讯失败:', err);
        setNewsError('网络请求失败，使用默认资讯数据');
        setIndustryNews([]);
      } finally {
        setNewsLoading(false);
      }
    };

    fetchIndustryNews();
  }, []);

  // 获取产品大类数据
  useEffect(() => {
    if (!isInitialized) return;
    
    const fetchCategories = async () => {
      try {
        const response = await ApiService.getMainCategoryList();
        
        if (response.code === '0000' && response.data) {
          // 按serNum排序
          const sortedCategories = response.data.sort((a, b) => a.serNum - b.serNum);
          setCategories(sortedCategories);
          
          // 为每个大类获取产品列表
          const categoryPromises = sortedCategories.map(async (category) => {
            try {
              const productResponse = await ApiService.getCategoryProductList(category.categoryId);
              if (productResponse.code === '0000' && productResponse.data) {
                // 只取前4个产品
                const products = productResponse.data
                  .sort((a, b) => a.serNum - b.serNum)
                  .slice(0, 6)
                  .map(product => ({
                    id: product.productId,
                    title: product.productName,
                    description: `${product.productSimDesc || ''}`,
                    image: product.picUrl || '📦', // 如果没有图片URL，使用默认图标
                    picUrl: product.picUrl
                  }));
                return { ...category, products };
              }
              return { ...category, products: [] };
            } catch (err) {
              console.error(`获取${category.categoryName}产品失败:`, err);
              return { ...category, products: [] };
            }
          });
          
          const categoriesWithProducts = await Promise.all(categoryPromises);
          setCategories(categoriesWithProducts);
        } else {
          console.error('获取产品大类失败:', response);
        }
      } catch (err) {
        console.error('获取产品大类失败:', err);
      }
    };

    fetchCategories();
  }, [isInitialized]);



  return (
    <div className="product-section">
      <div className="container">
        {/* 热门产品和行业资讯 */}
        <div className="hot-section">
          {/* 热门产品 */}
          <section className="hot-products">
            <div className="section-header">
              <h2>热门产品</h2>
              <button className="view-more-btn" onClick={() => handleViewMore('hot')}>查看更多 →</button>
            </div>
            
            {loading ? (
              <Spin></Spin>
            ) : error ? (
              <div className="error-container">
                <p className="error-message">{error}</p>
              </div>
            ) : (
                <div className="product-scroller">
                  <Slider
                    {...{
                      dots: false,
                      infinite: true,
                      speed: 500,
                      slidesToShow: 4,
                      slidesToScroll: 1,
                      autoplay: true,
                      autoplaySpeed: 3000,
                      pauseOnHover: true,
                      arrows: false,
                      responsive: [
                        {
                          breakpoint: 1024,
                          settings: {
                            slidesToShow: 3,
                          }
                        },
                        {
                          breakpoint: 768,
                          settings: {
                            slidesToShow: 2,
                          }
                        },
                        {
                          breakpoint: 480,
                          settings: {
                            slidesToShow: 1,
                          }
                        }
                      ]
                    }}
                  >
                    {hotProducts.map(product => (
                      <div key={product.id} className="slider-item">
                        <ProductCard product={product} />
                      </div>
                    ))}
                  </Slider>
                </div>
            )}
          </section>

          {/* 行业资讯 */}
          <section className="industry-news">
            <div className="section-header">
              <h2>行业资讯</h2>
              <button className="view-more-btn" onClick={() => navigate('/news')}>查看更多 →</button>
            </div>
            
            {newsLoading ? (
              <Spin></Spin>
            ) : newsError ? (
              <div className="error-container">
                <p className="error-message">{newsError}</p>
              </div>
            ) : (
              <div className="news-scroller">
                <Slider
                  {...{
                    vertical: true,
                    verticalSwiping: true,
                    dots: false,
                    infinite: true,
                    speed: 500,
                    slidesToShow: 6,
                    slidesToScroll: 1,
                    autoplay: true,
                    autoplaySpeed: 3000,
                    pauseOnHover: true,
                    arrows: false,
                  }}
                >
                  {industryNews.map(news => (
                    <div key={news.id} className="news-slide">
                      <div
                        className="news-item"
                        onClick={() => handleNewsClick(news.id)}
                      >
                        <div className="news-title">{news.title}</div>
                        <div className="news-date">{news.date}</div>
                      </div>
                    </div>
                  ))}
                </Slider>
              </div>
            )}
          </section>
        </div>

        {/* 产品大类 */}
        {categories.map(category => (
          <section key={category.categoryId} className="category-products">
            <div className="section-header">
              <h2>{category.categoryName}</h2>
              <button className="view-more-btn" onClick={() => handleViewMore('category', category.categoryId)}>查看更多 →</button>
            </div>
            <div className="category-product-grid">
              {category.products && category.products.length > 0 ? (
                category.products.map(product => (
                  <ProductCard key={product.id} product={product} />
                ))
              ) : (
                <div className="no-products">
                  <p>暂无产品</p>
                </div>
              )}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
};

export default ProductSection;
